//
//  DataManager.swift
//  CMB250716
//
//  Created by Andy Lau on 16/7/25.
//

import Foundation
import Combine
import LocalAuthentication
import UIKit

class DataManager: ObservableObject {
    static let shared = DataManager()
    
    // 现金券代码常量
    private static let cashVoucherCodes = AppConfig.CashVoucherPackage.voucherCodes
    
    // 限时折扣管理器
    private let limitedTimeDiscountManager = LimitedTimeDiscountManager.shared
    
    @Published var currentUser: User?
    @Published var isGuestMode: Bool = false
    @Published var menuItems: [MenuItem] = []
    @Published var cartItems: [CartItem] = []
    @Published var orders: [Order] = []
    @Published var availableCoupons: [Coupon] = []
    @Published var ownedCoupons: [UserCoupon] = []
    @Published var ownedCashVouchers: [String: Int] = [:] // 现金券数量，键为面额，值为数量

    @Published var currentLanguage: String = AppConfig.defaultLanguage // 默认英文，用户反馈在英文界面
    @Published var currentTableNumber: String?
    @Published var selectedDiningType: DiningType = .dineIn
    @Published var preSelectedCoupon: Coupon? // 用于从优惠券详情页面预选优惠券
    
    // 验证码管理
    @Published var pendingVerifications: [VerificationRecord] = []
    @Published var showingBiometricSetup: Bool = false
    @Published var biometricAuthenticationResult: Bool = false
    
    // 通知系统
    @Published var showingCouponUnlockNotification: Bool = false
    @Published var couponUnlockNotificationMessage: String = ""
    @Published var shouldNavigateToAllCoupons: Bool = false
    @Published var showingCouponUnlockAlert: Bool = false
    @Published var couponUnlockAlertMessage: String = ""
    
    // 导航控制
    @Published var shouldNavigateToOrdersCurrent: Bool = false
    @Published var shouldNavigateToOrdersHistory: Bool = false
    
    private init() {
        // 立即设置基本状态，避免启动延迟
        setupLanguage()
        logout() // 清除登录状态
        
        // 快速启动模式：优先加载关键数据
        if LaunchConfig.enableFastLaunch {
            loadCriticalDataFast()
        } else {
            loadDataTraditional()
        }
    }
    
    /// 快速加载关键数据
    private func loadCriticalDataFast() {
        // 使用高优先级后台队列快速加载
        DispatchQueue.global(qos: .userInitiated).async {
            // 加载优惠券数据
            let coupons = CouponConfig.coupons.map { $0.toCoupon() }
            
            // 立即更新UI关键数据
            DispatchQueue.main.async {
                // 不再加载硬编码菜单数据，完全依赖API
                self.menuItems = [] // 初始为空，等待API数据
                self.availableCoupons = coupons
                
                // 立即从API获取菜单数据
                self.fetchMenuItemsFromAPI()
            }
            
            // 延迟加载非关键数据
            if LaunchConfig.enableLazyLoading {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                    self.loadNonCriticalData()
                }
            } else {
                DispatchQueue.main.async {
                    self.loadNonCriticalData()
                }
            }
        }
    }
    
    /// 传统数据加载方式
    private func loadDataTraditional() {
        // 将耗时操作移到后台线程执行
        DispatchQueue.global(qos: .userInitiated).async {
            // 后台加载数据
            let coupons = CouponConfig.coupons.map { $0.toCoupon() }
            
            // 在主线程更新UI
            DispatchQueue.main.async {
                // 不再加载硬编码菜单数据，完全依赖API
                self.menuItems = [] // 初始为空，等待API数据
                self.availableCoupons = coupons
                
                // 立即从API获取菜单数据
                self.fetchMenuItemsFromAPI()
                
                self.loadNonCriticalData()
            }
        }
    }
    
    /// 加载非关键数据
    private func loadNonCriticalData() {
        loadUserOrders()
        
        // 清除98435556用户的社交互动积分记录并设置积分为168
        clearUserInteractionPoints(phoneNumber: "98435556")
        setUserPoints(phoneNumber: "98435556", points: 168)
    }
    
    // MARK: - Language Management
    private func setupLanguage() {
        // 强制设置为英文，根据用户反馈要求
        currentLanguage = "en"
    }
    
    func switchLanguage() {
        currentLanguage = currentLanguage == "zh" ? "en" : "zh"
    }
    
    func setLanguage(_ language: String) {
        currentLanguage = language
    }
    
    // MARK: - Menu Management
    
    /// 从API获取最新菜单数据
    func fetchMenuItemsFromAPI() {
        fetchMenuItemsFromAPI(retryCount: 3)
    }
    
    /// 从API获取最新菜单数据（带重试机制）
    private func fetchMenuItemsFromAPI(retryCount: Int) {
        if AppConfig.enableDebugLogging {
            print("[DataManager] 开始从API获取菜单数据 (剩余重试次数: \(retryCount))")
        }
        
        APIClient.shared.fetchMenuItems { [weak self] menuItems, error in
            guard let self = self else { return }
            
            if let error = error {
                if AppConfig.enableDebugLogging {
                    print("[DataManager] 获取菜单数据失败: \(error.localizedDescription)")
                }
                
                // 如果还有重试次数，则重试
                if retryCount > 0 {
                    if AppConfig.enableDebugLogging {
                        print("[DataManager] 将在2秒后重试...")
                    }
                    DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
                        self.fetchMenuItemsFromAPI(retryCount: retryCount - 1)
                    }
                } else {
                    if AppConfig.enableDebugLogging {
                        print("[DataManager] 所有重试都失败，使用空菜单数据")
                    }
                    DispatchQueue.main.async {
                        // 确保UI显示空状态而不是崩溃
                        self.menuItems = []
                    }
                }
                return
            }
            
            guard let menuItems = menuItems, !menuItems.isEmpty else {
                if AppConfig.enableDebugLogging {
                    print("[DataManager] API返回的菜单数据为空")
                }
                
                // 如果API返回空数据，也进行重试
                if retryCount > 0 {
                    if AppConfig.enableDebugLogging {
                        print("[DataManager] API返回空数据，将在2秒后重试...")
                    }
                    DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
                        self.fetchMenuItemsFromAPI(retryCount: retryCount - 1)
                    }
                } else {
                    if AppConfig.enableDebugLogging {
                        print("[DataManager] 所有重试都返回空数据")
                    }
                    DispatchQueue.main.async {
                        self.menuItems = []
                    }
                }
                return
            }
            
            if AppConfig.enableDebugLogging {
                print("[DataManager] 成功从API获取 \(menuItems.count) 个菜单项")
            }
            
            // 在主线程更新UI
            DispatchQueue.main.async {
                // 更新菜单数据
                self.menuItems = menuItems
                if AppConfig.enableDebugLogging {
                    print("[DataManager] 菜单数据已更新，B端管理系统现在完全控制C端菜单显示")
                }
            }
        }
    }
    
    /// 手动刷新菜单数据
    func refreshMenuItems() {
        fetchMenuItemsFromAPI()
    }
    
    // MARK: - User Management
    func loginUser(phoneNumber: String, verificationCode: String, inviteCode: String? = nil) -> Bool {
        // 模拟验证码验证 (6位数字)
        if verificationCode == "123456" {
            if let existingUser = loadUser(phoneNumber: phoneNumber) {
                var updatedUser = existingUser
                // 通过WhatsApp短信认证登录后，自动设置手机号为已验证状态
                updatedUser.isPhoneVerified = true
                currentUser = updatedUser
                
                // 为Level 1会员确保拥有基础礼券（包括已存在的用户）
                grantInitialCouponsForNewUser()
                
                saveUser(updatedUser)
            } else {
                // 验证邀请码并获取推荐人ID
                let referrerID = validateInviteCode(inviteCode)
                var newUser = User(phoneNumber: phoneNumber, referrerID: referrerID)
                // 通过WhatsApp短信认证登录后，自动设置手机号为已验证状态
                newUser.isPhoneVerified = true
                currentUser = newUser
                
                // 为新注册的Level 1会员分配初始优惠券
                grantInitialCouponsForNewUser()
                
                // 如果有有效的邀请码，处理邀请奖励
                if let referrerID = referrerID {
                    processInviteReward(referrerID: referrerID, newUserID: currentUser!.memberID)
                }
                
                saveUser(currentUser!)
            }
            isGuestMode = false
            return true
        }
        return false
    }
    
    func loginAsGuest() {
        currentUser = nil
        isGuestMode = true
    }
    
    func logout() {
        currentUser = nil
        isGuestMode = false
        cartItems.removeAll()
        currentTableNumber = nil
    }
    
    private func loadUser(phoneNumber: String) -> User? {
        // 首先检查是否是预设测试账号
        if let testUser = loadTestUser(phoneNumber: phoneNumber) {
            return testUser
        }
        
        // 从UserDefaults加载用户数据
        let key = AppConfig.StorageKeys.userPrefix + phoneNumber
        if let userData = UserDefaults.standard.data(forKey: key) {
            do {
                let user = try JSONDecoder().decode(User.self, from: userData)
                return user
            } catch {
                return nil
            }
        }
        return nil
    }
    
    private func saveUser(_ user: User) {
        // 保存用户数据到UserDefaults
        let key = AppConfig.StorageKeys.userPrefix + user.phoneNumber
        do {
            let userData = try JSONEncoder().encode(user)
            UserDefaults.standard.set(userData, forKey: key)
        } catch {
            // 保存失败，静默处理
        }
    }
    
    // 公共方法：保存当前用户数据
    func saveUser() {
        guard let user = currentUser else {
            return
        }
        saveUser(user)
    }
    
    // MARK: - 测试数据预设
    private func loadTestUser(phoneNumber: String) -> User? {
        switch phoneNumber {
        case "88888888":
            return createTestUser(
                phoneNumber: "88888888",
                name: "测试小牛",
                points: 0,
                totalPoints: 0,
                level: .lv1
            )
        case "66666666":
            return createTestUser(
                phoneNumber: "66666666",
                name: "测试银牛",
                points: 0,
                totalPoints: 0,
                level: .lv2
            )
        case "99999999":
            return createTestUser(
                phoneNumber: "99999999",
                name: "测试金牛",
                points: 0,
                totalPoints: 0,
                level: .lv3
            )
        case "77777777":
            return createTestUser(
                phoneNumber: "77777777",
                name: "测试神牛",
                points: 0,
                totalPoints: 0,
                level: .lv4
            )
        case "98435556":
            return createTestUser(
                phoneNumber: "98435556",
                name: "测试用户",
                points: 168,
                totalPoints: 168,
                level: .lv1
            )
        default:
            return nil
        }
    }
    
    private func createTestUser(phoneNumber: String, name: String, points: Int, totalPoints: Int, level: MembershipLevel) -> User {
        var user = User(phoneNumber: phoneNumber, name: name)
        user.points = points
        user.totalPointsEarned = totalPoints
        user.membershipLevel = level
        user.email = "\(name)@test.com"
        user.birthYear = "1990"
        user.birthMonth = "01"
        
        // 统一测试账户优惠券逻辑：只为Level 1测试账户添加基础优惠券
        // 其他等级的测试账户不预设优惠券，保持与普通会员账户一致的显示逻辑
        if level == .lv1 {
            let basicCoupons = [
                UserCoupon(
                    couponCode: "NEWMEMBER5",
                    grantedDate: Date(),
                    relativeDuration: .days(30)
                ),
                UserCoupon(
                    couponCode: "WEEKEND50",
                    grantedDate: Date(),
                    relativeDuration: .days(30)
                ),
                UserCoupon(
                    couponCode: "HIGHBALL",
                    grantedDate: Date(),
                    relativeDuration: .days(30)
                ),
                UserCoupon(
                    couponCode: "CALFCOFFEE",
                    grantedDate: Date(),
                    relativeDuration: .days(30)
                ),
                UserCoupon(
                    couponCode: "MYSTERYGIFT",
                    grantedDate: Date(),
                    relativeDuration: .days(30)
                ),
                // 添加现金券用于测试badge显示
                UserCoupon(
                    couponCode: "CASH_VOUCHER_1",
                    grantedDate: Date(),
                    relativeDuration: .years(1)
                ),
                UserCoupon(
                    couponCode: "CASH_VOUCHER_1",
                    grantedDate: Date(),
                    relativeDuration: .years(1)
                ),
                UserCoupon(
                    couponCode: "CASH_VOUCHER_2",
                    grantedDate: Date(),
                    relativeDuration: .years(1)
                ),
                UserCoupon(
                    couponCode: "CASH_VOUCHER_2",
                    grantedDate: Date(),
                    relativeDuration: .years(1)
                ),
                UserCoupon(
                    couponCode: "CASH_VOUCHER_2",
                    grantedDate: Date(),
                    relativeDuration: .years(1)
                ),
                UserCoupon(
                    couponCode: "CASH_VOUCHER_3",
                    grantedDate: Date(),
                    relativeDuration: .years(1)
                )
            ]
            user.ownedCoupons = basicCoupons
        } else {
            // 高等级测试账户不预设优惠券，让解锁逻辑与普通会员保持一致
            user.ownedCoupons = []
        }
        
        // 添加测试社交媒体账号
        user.socialMediaAccounts = SocialMediaAccounts(
            instagram: "@\(name.lowercased())",
            facebook: name,
            tiktok: "@\(name.lowercased())"
        )
        
        return user
    }
    
    func updateUserInfo(name: String, email: String, birthYear: String, birthMonth: String) {
        guard var user = currentUser else { return }
        
        // 检查更新前的会员信息完善状态
        let wasInfoComplete = user.isMemberInfoComplete
        
        user.name = name
        user.email = email
        user.birthYear = birthYear
        user.birthMonth = birthMonth
        
        currentUser = user
        saveUser(user)
        
        // 如果之前信息不完善，现在完善了，激活会员信息完善礼券
        if !wasInfoComplete && user.isMemberInfoComplete {
            activateMemberInfoCompletionCoupon()
        }
    }
    
    // MARK: - 验证码管理
    func sendVerificationCode(for type: VerificationType) -> String {
        let code = String(format: "%06d", Int.random(in: 100000...999999))
        let verification = VerificationRecord(type: type, code: code)
        pendingVerifications.append(verification)
        
        // 模拟发送验证码
        switch type {
        case .phoneChange(_, _):
            break
        case .emailChange(_, _):
            break
        case .login(_):
            break
        case .biometricSetup:
            break
        }
        
        return code
    }
    
    func verifyCode(_ inputCode: String, for type: VerificationType) -> Bool {
        // 测试验证码：手机变更功能使用固定验证码 123456
        if inputCode == "123456" {
            switch type {
            case .phoneChange(_, _):
                return true
            default:
                break
            }
        }
        
        guard let index = pendingVerifications.firstIndex(where: { 
            verification in
            verification.isValid && verification.code == inputCode &&
            compareVerificationType(verification.type, type)
        }) else {
            return false
        }
        
        pendingVerifications[index].isUsed = true
        return true
    }
    
    private func compareVerificationType(_ type1: VerificationType, _ type2: VerificationType) -> Bool {
        switch (type1, type2) {
        case (.phoneChange(let old1, let new1), .phoneChange(let old2, let new2)):
            return old1 == old2 && new1 == new2
        case (.emailChange(let old1, let new1), .emailChange(let old2, let new2)):
            return old1 == old2 && new1 == new2
        case (.login(let phone1), .login(let phone2)):
            return phone1 == phone2
        case (.biometricSetup, .biometricSetup):
            return true
        default:
            return false
        }
    }
    
    // MARK: - 换绑功能
    func canChangePhone() -> (canChange: Bool, reason: String?) {
        guard let user = currentUser else {
            return (false, "用户未登录")
        }
        
        if let lastChangeDate = user.lastPhoneChangeDate {
            let daysSinceLastChange = Calendar.current.dateComponents([.day], from: lastChangeDate, to: Date()).day ?? 0
            if daysSinceLastChange < 1 {
                return (false, "24小时内不可重复修改手机号")
            }
        }
        
        return (true, nil)
    }
    
    func canChangeEmail() -> (canChange: Bool, reason: String?) {
        guard let user = currentUser else {
            return (false, "用户未登录")
        }
        
        if let lastChangeDate = user.lastEmailChangeDate {
            let daysSinceLastChange = Calendar.current.dateComponents([.day], from: lastChangeDate, to: Date()).day ?? 0
            if daysSinceLastChange < 1 {
                return (false, "24小时内不可重复修改邮箱")
            }
        }
        
        return (true, nil)
    }
    
    func changePhoneNumber(newPhone: String, oldPhoneCode: String, newPhoneCode: String) -> Bool {
        guard var user = currentUser else { return false }
        
        let canChange = canChangePhone()
        guard canChange.canChange else { return false }
        
        let oldPhoneType = VerificationType.phoneChange(oldPhone: user.phoneNumber, newPhone: newPhone)
        let newPhoneType = VerificationType.phoneChange(oldPhone: user.phoneNumber, newPhone: newPhone)
        
        guard verifyCode(oldPhoneCode, for: oldPhoneType) && verifyCode(newPhoneCode, for: newPhoneType) else {
            return false
        }
        
        // 记录换绑历史
        let changeRecord = ContactChangeRecord(
            oldValue: user.phoneNumber,
            newValue: newPhone,
            verificationMethod: "SMS"
        )
        user.phoneChangeHistory.append(changeRecord)
        user.lastPhoneChangeDate = Date()
        
        // 更新手机号
        let oldPhoneNumber = user.phoneNumber
        user = User(phoneNumber: newPhone, name: user.name, email: user.email)
        user.points = currentUser!.points
        user.totalPointsEarned = currentUser!.totalPointsEarned
        user.membershipLevel = currentUser!.membershipLevel
        user.phoneChangeHistory = currentUser!.phoneChangeHistory
        user.emailChangeHistory = currentUser!.emailChangeHistory
        user.lastPhoneChangeDate = Date()
        user.lastEmailChangeDate = currentUser!.lastEmailChangeDate
        
        // 删除旧用户数据
        let oldKey = AppConfig.StorageKeys.userPrefix + oldPhoneNumber
        UserDefaults.standard.removeObject(forKey: oldKey)
        
        currentUser = user
        saveUser(user)
        
        return true
    }
    
    func changeEmail(newEmail: String, oldEmailCode: String, newEmailCode: String) -> Bool {
        guard var user = currentUser else { return false }
        
        let canChange = canChangeEmail()
        guard canChange.canChange else { return false }
        
        let oldEmail = user.email ?? ""
        let oldEmailType = VerificationType.emailChange(oldEmail: oldEmail, newEmail: newEmail)
        let newEmailType = VerificationType.emailChange(oldEmail: oldEmail, newEmail: newEmail)
        
        guard verifyCode(oldEmailCode, for: oldEmailType) && verifyCode(newEmailCode, for: newEmailType) else {
            return false
        }
        
        // 记录换绑历史
        let changeRecord = ContactChangeRecord(
            oldValue: oldEmail,
            newValue: newEmail,
            verificationMethod: "Email"
        )
        user.emailChangeHistory.append(changeRecord)
        user.lastEmailChangeDate = Date()
        user.email = newEmail
        user.isEmailVerified = true
        
        currentUser = user
        saveUser(user)
        
        return true
    }
    
    // MARK: - 生物识别登录
    func isBiometricAvailable() -> Bool {
        let context = LAContext()
        var error: NSError?
        let isAvailable = context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error)
        
        if AppConfig.enableDebugLogging {
            print("[DEBUG] DataManager.isBiometricAvailable: \(isAvailable), 错误: \(error?.localizedDescription ?? "无")")
        }
        
        return isAvailable
    }
    
    func getBiometricType() -> String {
        let context = LAContext()
        var error: NSError?
        
        guard context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) else {
            return "不支持"
        }
        
        switch context.biometryType {
        case .faceID:
            return "Face ID"
        case .touchID:
            return "Touch ID"
        case .opticID:
            return "Optic ID"
        default:
            return "生物识别"
        }
    }
    
    func authenticateWithBiometrics(completion: @escaping (Bool, String?) -> Void) {
        // 安全检查：确保生物识别可用
        guard isBiometricAvailable() else {
            if AppConfig.enableDebugLogging {
                print("[DEBUG] DataManager.authenticateWithBiometrics: 生物识别不可用")
            }
            DispatchQueue.main.async {
                completion(false, "生物识别功能不可用")
            }
            return
        }
        
        let context = LAContext()
        // 设置更友好的提示文本
        let reason = currentLanguage == "zh" ? "使用\(getBiometricType())快速登录" : "Use \(getBiometricType()) to login quickly"
        
        // 添加错误处理和调试日志
        if AppConfig.enableDebugLogging {
            print("[DEBUG] DataManager.authenticateWithBiometrics: 开始生物识别验证")
        }
        
        // 设置取消按钮文本
        context.localizedCancelTitle = currentLanguage == "zh" ? "取消" : "Cancel"
        context.localizedFallbackTitle = currentLanguage == "zh" ? "使用密码" : "Use Password"
        
        context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { success, error in
            DispatchQueue.main.async {
                if AppConfig.enableDebugLogging {
                    print("[DEBUG] DataManager.authenticateWithBiometrics: 验证结果 - 成功: \(success)")
                    if let error = error {
                        print("[DEBUG] DataManager.authenticateWithBiometrics: 错误详情: \(error.localizedDescription)")
                    }
                }
                
                if success {
                    completion(true, nil)
                } else {
                    let errorMessage = error?.localizedDescription ?? (self.currentLanguage == "zh" ? "生物识别验证失败" : "Biometric authentication failed")
                    completion(false, errorMessage)
                }
            }
        }
    }
    
    func enableBiometricLogin() {
        guard var user = currentUser else { 
            if AppConfig.enableDebugLogging {
                print("[DEBUG] DataManager.enableBiometricLogin: 失败 - 没有当前用户")
            }
            return 
        }
        
        let wasEnabled = user.biometricLoginEnabled
        user.biometricLoginEnabled = true
        user.loginDeviceId = UIDevice.current.identifierForVendor?.uuidString
        currentUser = user
        saveUser(user)
        
        // 更新生物识别用户标记
        updateBiometricUsersFlag()
        
        if AppConfig.enableDebugLogging {
            print("[DEBUG] DataManager.enableBiometricLogin: 成功 - 用户ID: \(user.id), 手机号: \(user.phoneNumber), 之前状态: \(wasEnabled), 当前状态: \(user.biometricLoginEnabled)")
        }
    }
    
    func disableBiometricLogin() {
        guard var user = currentUser else { 
            if AppConfig.enableDebugLogging {
                print("[DEBUG] DataManager.disableBiometricLogin: 失败 - 没有当前用户")
            }
            return 
        }
        
        let wasEnabled = user.biometricLoginEnabled
        user.biometricLoginEnabled = false
        user.loginDeviceId = nil
        currentUser = user
        saveUser(user)
        
        // 检查是否还有其他用户启用了生物识别
        updateBiometricUsersFlag()
        
        if AppConfig.enableDebugLogging {
            print("[DEBUG] DataManager.disableBiometricLogin: 成功 - 用户ID: \(user.id), 手机号: \(user.phoneNumber), 之前状态: \(wasEnabled), 当前状态: \(user.biometricLoginEnabled)")
        }
    }
    
    // 检查是否有任何用户启用了生物识别登录
    func hasAnyBiometricCredentials() -> Bool {
        if AppConfig.enableDebugLogging {
            print("[DEBUG] DataManager.hasAnyBiometricCredentials() - 检查是否有生物识别凭据")
        }
        
        // 检查UserDefaults中是否有生物识别启用记录
        let hasBiometricUsers = UserDefaults.standard.bool(forKey: "hasBiometricEnabledUsers")
        
        if AppConfig.enableDebugLogging {
            print("[DEBUG] DataManager.hasAnyBiometricCredentials() - 结果: \(hasBiometricUsers)")
        }
        
        return hasBiometricUsers
    }
    
    // 获取启用了生物识别的用户列表
    func getBiometricEnabledUsers() -> [User] {
        if AppConfig.enableDebugLogging {
            print("[DEBUG] DataManager.getBiometricEnabledUsers() - 获取启用生物识别的用户列表")
        }
        
        var biometricUsers: [User] = []
        let allPhones = getAllRegisteredPhones()
        
        for phone in allPhones {
            if let user = loadUser(phoneNumber: phone), user.biometricLoginEnabled == true {
                biometricUsers.append(user)
            }
        }
        
        if AppConfig.enableDebugLogging {
            print("[DEBUG] DataManager.getBiometricEnabledUsers() - 找到 \(biometricUsers.count) 个启用生物识别的用户")
        }
        
        return biometricUsers
    }
    
    // 更新生物识别用户标记
    private func updateBiometricUsersFlag() {
        let biometricUsers = getBiometricEnabledUsers()
        let hasBiometricUsers = !biometricUsers.isEmpty
        UserDefaults.standard.set(hasBiometricUsers, forKey: "hasBiometricEnabledUsers")
        
        if AppConfig.enableDebugLogging {
            print("[DEBUG] DataManager.updateBiometricUsersFlag() - 更新标记: \(hasBiometricUsers)")
        }
    }
    
    // MARK: - 持久化登录
    func generateAuthToken() -> String {
        return UUID().uuidString + "-" + String(Date().timeIntervalSince1970)
    }
    
    func loginUserWithPersistence(phoneNumber: String, verificationCode: String) -> Bool {
        if loginUser(phoneNumber: phoneNumber, verificationCode: verificationCode) {
            guard var user = currentUser else { return false }
            
            // 生成JWT Token
            user.authToken = generateAuthToken()
            user.tokenExpiryDate = Calendar.current.date(byAdding: .day, value: 30, to: Date())
            user.lastLoginDate = Date()
            user.loginDeviceId = UIDevice.current.identifierForVendor?.uuidString
            
            currentUser = user
            saveUser(user)
            
            // 保存持久化登录信息
            UserDefaults.standard.set(phoneNumber, forKey: "persistentLoginPhone")
            UserDefaults.standard.set(user.authToken, forKey: "persistentLoginToken")
            
            // 设置APIClient的认证令牌
            APIClient.shared.setAuthToken(user.authToken)
            
            // 加载用户的订单历史
            loadOrdersForUser(userId: user.id)
            
            // 注释：生物识别设置现在通过LoginView控制，不再在这里自动触发
            
            return true
        }
        return false
    }
    
    func tryAutoLogin() -> Bool {
        guard let savedPhone = UserDefaults.standard.string(forKey: "persistentLoginPhone"),
              let savedToken = UserDefaults.standard.string(forKey: "persistentLoginToken"),
              let user = loadUser(phoneNumber: savedPhone),
              let userToken = user.authToken,
              let tokenExpiry = user.tokenExpiryDate else {
            return false
        }
        
        // 检查token是否有效
        guard userToken == savedToken && Date() < tokenExpiry else {
            clearPersistentLogin()
            return false
        }
        
        // 检查设备ID
        let currentDeviceId = UIDevice.current.identifierForVendor?.uuidString
        guard user.loginDeviceId == currentDeviceId else {
            clearPersistentLogin()
            return false
        }
        
        currentUser = user
        isGuestMode = false
        
        // 设置APIClient的认证令牌
        APIClient.shared.setAuthToken(userToken)
        
        return true
    }
    
    func tryBiometricLogin(completion: @escaping (Bool) -> Void) {
        // 添加主线程检查
        guard Thread.isMainThread else {
            DispatchQueue.main.async {
                self.tryBiometricLogin(completion: completion)
            }
            return
        }
        
        // 安全检查：确保有当前用户且启用了生物识别
        guard let user = currentUser, user.biometricLoginEnabled else {
            if AppConfig.enableDebugLogging {
                print("[DEBUG] DataManager.tryBiometricLogin: 失败 - 没有当前用户或未启用生物识别")
            }
            DispatchQueue.main.async {
                completion(false)
            }
            return
        }
        
        // 额外安全检查：确保生物识别功能可用
        guard isBiometricAvailable() else {
            if AppConfig.enableDebugLogging {
                print("[DEBUG] DataManager.tryBiometricLogin: 失败 - 生物识别功能不可用")
            }
            DispatchQueue.main.async {
                completion(false)
            }
            return
        }
        
        if AppConfig.enableDebugLogging {
            print("[DEBUG] DataManager.tryBiometricLogin: 开始为用户 \(user.phoneNumber) 进行生物识别登录")
        }
        
        authenticateWithBiometrics { [weak self] success, error in
            guard let self = self else {
                DispatchQueue.main.async {
                    completion(false)
                }
                return
            }
            
            // 确保在主线程上执行UI更新
            DispatchQueue.main.async {
                if success {
                    if AppConfig.enableDebugLogging {
                        print("[DEBUG] DataManager.tryBiometricLogin: 成功 - 更新用户登录状态")
                    }
                    // 更新最后登录时间
                    var updatedUser = user
                    updatedUser.lastLoginDate = Date()
                    self.currentUser = updatedUser
                    self.saveUser(updatedUser)
                    self.isGuestMode = false
                } else {
                    if AppConfig.enableDebugLogging {
                        print("[DEBUG] DataManager.tryBiometricLogin: 失败 - \(error ?? "未知错误")")
                    }
                }
                completion(success)
            }
        }
    }
    
    func clearPersistentLogin() {
        UserDefaults.standard.removeObject(forKey: "persistentLoginPhone")
        UserDefaults.standard.removeObject(forKey: "persistentLoginToken")
        
        // 清除APIClient的认证令牌
        APIClient.shared.setAuthToken(nil)
        
        if var user = currentUser {
            user.authToken = nil
            user.tokenExpiryDate = nil
            currentUser = user
            saveUser(user)
        }
    }
    
    func logoutUser() {
        clearPersistentLogin()
        currentUser = nil
        isGuestMode = false
        cartItems.removeAll()
        currentTableNumber = nil
    }
    
    // MARK: - Cart Management
    
    // 购物车管理相关状态变量已移除，现在使用自动替换逻辑
    
    func addToCart(_ menuItem: MenuItem, quantity: Int = 1, meatType: MeatType? = nil, spicyLevel: SpicyLevel? = nil, specialInstructions: String = "", priceOption: PriceOption? = nil) {
        // 检查是否为Cash Voucher
        let isCashVoucher = menuItem.name == AppConfig.Cart.voucherPackageName
        
        // 处理购物车冲突的自动替换逻辑
        if isCashVoucher {
            // 如果添加的是Cash Voucher，检查是否有其他商品，如果有则清空购物车
            let hasOtherItems = cartItems.contains { !isCashVoucherItem($0) }
            if hasOtherItems {
                cartItems.removeAll()
            }
        } else {
            // 如果添加的是正常菜品，检查是否有Cash Voucher，如果有则移除Cash Voucher
            cartItems.removeAll { isCashVoucherItem($0) }
        }
        
        // 直接添加到购物车
        addToCartDirectly(menuItem, quantity: quantity, meatType: meatType, spicyLevel: spicyLevel, specialInstructions: specialInstructions, priceOption: priceOption)
    }
    
    // 直接添加到购物车的内部方法
    private func addToCartDirectly(_ menuItem: MenuItem, quantity: Int = 1, meatType: MeatType? = nil, spicyLevel: SpicyLevel? = nil, specialInstructions: String = "", priceOption: PriceOption? = nil) {
        if let existingIndex = cartItems.firstIndex(where: { 
            $0.menuItem.id == menuItem.id && 
            $0.selectedMeatType == meatType && 
            $0.selectedSpicyLevel == spicyLevel &&
            $0.specialInstructions == specialInstructions &&
            $0.selectedPriceOption?.id == priceOption?.id
        }) {
            cartItems[existingIndex].quantity += quantity
        } else {
            let cartItem = CartItem(
                menuItem: menuItem,
                quantity: quantity,
                selectedMeatType: meatType,
                specialInstructions: specialInstructions,
                selectedPriceOption: priceOption,
                selectedSpicyLevel: spicyLevel
            )
            cartItems.append(cartItem)
        }
    }
    
    // clearCartAndAddPendingItem方法已移除，现在使用自动替换逻辑
    
    // 辅助方法：检查是否为Cash Voucher商品
    private func isCashVoucherItem(_ cartItem: CartItem) -> Bool {
        return cartItem.menuItem.name == AppConfig.Cart.voucherPackageName
    }
    
    func removeFromCart(_ cartItem: CartItem) {
        cartItems.removeAll { $0.id == cartItem.id }
    }
    
    func removeFromCart(_ menuItem: MenuItem) {
        cartItems.removeAll { $0.menuItem.id == menuItem.id }
    }
    
    func updateCartItemQuantity(_ cartItem: CartItem, quantity: Int) {
        if let index = cartItems.firstIndex(where: { $0.id == cartItem.id }) {
            if quantity <= 0 {
                cartItems.remove(at: index)
            } else {
                cartItems[index].quantity = quantity
            }
        }
    }
    
    func updateCartItemQuantity(_ menuItem: MenuItem, quantity: Int) {
        if let index = cartItems.firstIndex(where: { $0.menuItem.id == menuItem.id }) {
            if quantity <= 0 {
                cartItems.remove(at: index)
            } else {
                cartItems[index].quantity = quantity
            }
        }
    }
    
    func getItemQuantityInCart(_ menuItem: MenuItem) -> Int {
        return cartItems.first(where: { $0.menuItem.id == menuItem.id })?.quantity ?? 0
    }
    
    func clearCart() {
        cartItems.removeAll()
    }
    
    // MARK: - Reorder Functions
    func reorderItems(from order: Order) {
        clearCart()
        for orderItem in order.items {
            addToCart(
                orderItem.menuItem,
                quantity: orderItem.quantity,
                meatType: orderItem.selectedMeatType,
                spicyLevel: orderItem.selectedSpicyLevel,
                specialInstructions: orderItem.specialInstructions,
                priceOption: orderItem.selectedPriceOption
            )
        }
    }
    
    var cartTotal: Double {
        return calculateCartTotalWithDiscounts()
    }
    
    /// 计算购物车总价（包含限时折扣）
    private func calculateCartTotalWithDiscounts() -> Double {
        var total: Double = 0
        
        for cartItem in cartItems {
            var itemTotal = cartItem.totalPrice
            
            // 检查是否适用限时折扣
            if shouldApplyLimitedTimeDiscount(for: cartItem) {
                itemTotal = limitedTimeDiscountManager.calculateDiscountedPrice(itemTotal)
            }
            
            total += itemTotal
        }
        
        return total
    }
    
    /// 检查购物车项目是否适用限时折扣
    private func shouldApplyLimitedTimeDiscount(for cartItem: CartItem) -> Bool {
        // 检查是否在折扣时间段内
        guard limitedTimeDiscountManager.isCurrentlyInDiscountPeriod() else {
            return false
        }
        
        // 检查用户是否有资格
        guard limitedTimeDiscountManager.isUserEligibleForDiscount(currentUser) else {
            return false
        }
        
        // 检查订餐类型是否适用
        guard limitedTimeDiscountManager.isDiningTypeEligible(selectedDiningType) else {
            return false
        }
        
        // 检查商品是否适用折扣
        return limitedTimeDiscountManager.isItemEligibleForDiscount(cartItem.menuItem)
    }
    
    /// 获取购物车项目的显示价格（用于UI显示）
    func getDisplayPrice(for cartItem: CartItem) -> (originalPrice: Double, discountedPrice: Double?, hasDiscount: Bool) {
        let originalPrice = cartItem.totalPrice
        
        if shouldApplyLimitedTimeDiscount(for: cartItem) {
            let discountedPrice = limitedTimeDiscountManager.calculateDiscountedPrice(originalPrice)
            return (originalPrice, discountedPrice, true)
        }
        
        return (originalPrice, nil, false)
    }
    
    /// 检查当前是否有限时折扣活动
    func isLimitedTimeDiscountActive() -> Bool {
        return limitedTimeDiscountManager.isCurrentlyInDiscountPeriod() &&
               limitedTimeDiscountManager.isUserEligibleForDiscount(currentUser) &&
               limitedTimeDiscountManager.isDiningTypeEligible(selectedDiningType)
    }
    
    var cartItemCount: Int {
        return cartItems.reduce(0) { $0 + $1.quantity }
    }
    
    // 计算当前活跃订单数量（不包括已完成和已取消的订单）
    var activeOrderCount: Int {
        return orders.filter { order in
            order.status != .completed && order.status != .cancelled
        }.count
    }
    
    // MARK: - Order Management
    func createOrder(paymentMethod: PaymentMethod, specialInstructions: String? = nil, appliedCoupon: Coupon? = nil, pointsUsed: Int = 0, reservationTime: Date? = nil, reservationInfo: ReservationConfig.ReservationInfo? = nil) -> Order {
        let userMembershipLevel = currentUser?.membershipLevel ?? .lv1
        
        // 检查是否只包含现金券套餐
        let hasOnlyCashVoucher = cartItems.allSatisfy { $0.menuItem.name == AppConfig.Cart.voucherPackageName }
        
        if hasOnlyCashVoucher {
            // 现金券购买逻辑：创建订单并立即设置为已完成状态
            let currentCartItems = cartItems // 保存当前购物车项目
            
            // 创建现金券套餐订单
            var order = Order(
                userId: currentUser?.id,
                tableNumber: currentTableNumber,
                items: currentCartItems,
                diningType: selectedDiningType,
                paymentMethod: paymentMethod,
                specialInstructions: specialInstructions,
                appliedCoupon: appliedCoupon,
                pointsUsed: pointsUsed,
                userMembershipLevel: userMembershipLevel,
                isReservation: reservationInfo != nil,
                reservationTime: reservationInfo?.reservationTime,
                reservationPartySize: reservationInfo?.partySize,
                reservationSeatingType: reservationInfo?.seatingType,
                reservationSpecialRequests: reservationInfo?.specialRequests
            )
            
            // 立即设置为已完成状态
            order.updateStatus(.completed)
            
            // 处理现金券发放
            processCashVoucherPurchase(paymentMethod: paymentMethod)
            
            // 保存订单到历史记录
            orders.append(order)
            clearCart()
            
            return order
        } else {
            // 普通订单逻辑
            let order = Order(
                userId: currentUser?.id,
                tableNumber: currentTableNumber,
                items: cartItems,
                diningType: selectedDiningType,
                paymentMethod: paymentMethod,
                specialInstructions: specialInstructions,
                appliedCoupon: appliedCoupon,
                pointsUsed: pointsUsed,
                userMembershipLevel: userMembershipLevel,
                isReservation: reservationInfo != nil,
                reservationTime: reservationInfo?.reservationTime,
                reservationPartySize: reservationInfo?.partySize,
                reservationSeatingType: reservationInfo?.seatingType,
                reservationSpecialRequests: reservationInfo?.specialRequests
            )
            
            // 先保存到本地
            orders.append(order)
            clearCart()
            
            // 提交订单到后端API
            APIClient.shared.submitOrder(order) { [weak self] success, error, backendOrderId in
                DispatchQueue.main.async {
                    guard let self = self else { return }
                    
                    if success {
                        if AppConfig.enableDebugLogging {
                            print("[DataManager] 订单已成功提交到后端: \(order.orderNumber)，后端ID: \(backendOrderId ?? -1)")
                        }
                        
                        // 更新本地订单的backendId
                        if let backendId = backendOrderId,
                           let index = self.orders.firstIndex(where: { $0.id == order.id }) {
                            self.orders[index].backendId = backendId
                            self.saveOrdersForCurrentUser()
                        }
                    } else {
                        if AppConfig.enableDebugLogging {
                            print("[DataManager] 订单提交到后端失败: \(error?.localizedDescription ?? "未知错误")")
                        }
                        // 注意：即使提交失败，订单仍然保存在本地，用户可以继续使用
                    }
                }
            }
            
            return order
        }
    }
    
    func updateOrderStatus(_ orderId: UUID, status: OrderStatus) {
        if let index = orders.firstIndex(where: { $0.id == orderId }) {
            orders[index].updateStatus(status)
            
            // 当状态为 .completed 且积分未发放时，添加积分
            if status == .completed && !orders[index].pointsAwarded {
                if var user = currentUser {
                    user.addPoints(orders[index].pointsEarned)
                    currentUser = user
                    saveUser(user)
                }
                orders[index].pointsAwarded = true
            }
            
            // 同步状态到后端
            if let backendId = orders[index].backendId {
                APIClient.shared.updateOrderStatus(backendId: backendId, status: status) { success, error in
                    DispatchQueue.main.async {
                        if success {
                            print("订单状态已成功同步到后端: \(backendId) -> \(status)")
                        } else {
                            print("订单状态同步到后端失败: \(backendId) - \(error?.localizedDescription ?? "未知错误")")
                        }
                    }
                }
            } else {
                print("订单缺少backendId，无法同步到后端: \(orderId)")
            }
        }
    }
    

    

    
    // MARK: - Coupon Management
    func grantCouponToUser(couponCode: String, relativeDuration: RelativeDuration) {
        guard var user = currentUser else { return }
        
        let userCoupon = UserCoupon(
            couponCode: couponCode,
            grantedDate: Date(),
            relativeDuration: relativeDuration
        )
        
        user.ownedCoupons.append(userCoupon)
        currentUser = user
        saveUser(user)
        
        // 查找对应的优惠券并显示解锁通知
        if let coupon = availableCoupons.first(where: { $0.code == couponCode }) {
            showCouponUnlockNotification(couponTitle: coupon.title)
        }
    }
    
    // 静默发放礼券，不显示通知
    private func grantCouponToUserSilently(couponCode: String, relativeDuration: RelativeDuration) {
        guard var user = currentUser else { return }
        
        let userCoupon = UserCoupon(
            couponCode: couponCode,
            grantedDate: Date(),
            relativeDuration: relativeDuration
        )
        
        user.ownedCoupons.append(userCoupon)
        currentUser = user
        saveUser(user)
    }
    
    func getAvailableCouponsForUser() -> [Coupon] {
        guard let user = currentUser else { return availableCoupons }
        
        return availableCoupons.filter { coupon in
            // 检查用户是否拥有此礼券
            let hasValidCoupon = user.ownedCoupons.contains { userCoupon in
                userCoupon.couponCode == coupon.code &&
                !userCoupon.isUsed &&
                userCoupon.expiryDate > Date()
            }
            
            // 如果用户没有有效的礼券，直接返回false
            guard hasValidCoupon else { return false }
            
            // 检查是否可以使用（时间和频率限制）
            let canUseBasedOnTime = user.canUseCoupon(coupon)
            
            // 对于周频率优惠券（CALFCOFFEE和HIGHBALL），额外检查使用频率
            if coupon.usageFrequency == .weekly {
                let calendar = Calendar.current
                guard let currentWeekInterval = calendar.dateInterval(of: .weekOfYear, for: Date()) else {
                    return canUseBasedOnTime
                }
                
                // 检查本周是否已使用过此优惠券
                let usedThisWeek = user.couponUsageHistory.contains { record in
                    record.couponCode == coupon.code &&
                    currentWeekInterval.contains(record.usedDate)
                }
                
                // 如果本周已使用，则不可用
                if usedThisWeek {
                    return false
                }
            }
            
            return canUseBasedOnTime
        }
    }
    
    // 获取真正可用的优惠券数量（已解锁且已激活的）
    func getAvailableCouponsCount() -> Int {
        guard let _ = currentUser else { return 0 }
        
        return availableCoupons.filter { coupon in
            let isUnlocked = isUserCouponUnlocked(coupon)
            let activationStatus = checkCouponActivation(coupon: coupon)
            return isUnlocked && activationStatus == .available
        }.count
    }
    
    // 获取所有优惠券（包括已解锁和未解锁的）
    func getAllCouponsForDisplay() -> [Coupon] {
        return availableCoupons.filter { coupon in
            // 使用CouponSelectionConfig的统一过滤逻辑，但不应用营业时间过滤
            // 营业时间过滤只在购物车选择时应用
            return CouponSelectionConfig.shouldShowCoupon(coupon, dataManager: self, isCartSelection: false)
        }
    }
    
    // 检查用户是否已解锁某个优惠券
    func isUserCouponUnlocked(_ coupon: Coupon) -> Bool {
        guard let user = currentUser else { return false }
        
        // 检查用户是否拥有此优惠券
        let hasValidCoupon = user.ownedCoupons.contains { userCoupon in
            userCoupon.couponCode == coupon.code &&
            !userCoupon.isUsed &&
            userCoupon.expiryDate > Date()
        }
        
        // 现金券特殊处理：只有用户拥有时才显示，不依赖isActive状态
        if Self.cashVoucherCodes.contains(coupon.code) {
            return hasValidCoupon
        }
        
        // 其他优惠券需要检查是否处于活跃状态
        guard coupon.isActive else { return false }
        
        if hasValidCoupon {
            return true
        }
        
        // 检查优惠券是否需要特定会员等级
        if let requiredLevel = coupon.requiresMembershipLevel {
            // 比较用户等级的英文名称与优惠券要求的等级
            let userLevelEnglish = user.membershipLevel.englishName
            // 如果用户等级高于或等于要求等级，则解锁
            let levelOrder = ["Neon Rookie", "Hype Blaze", "Vibe Regent", "Aureus Legend"]
            if let userIndex = levelOrder.firstIndex(of: userLevelEnglish),
               let requiredIndex = levelOrder.firstIndex(of: requiredLevel) {
                return userIndex >= requiredIndex
            }
            return userLevelEnglish == requiredLevel
        }
        
        // 基础优惠券解锁逻辑：所有会员都可以解锁基础优惠券（不需要特定等级的优惠券）
        let basicCoupons = ["NEWMEMBER5", "WEEKEND50", "HIGHBALL", "CALFCOFFEE", "MYSTERYGIFT", "FUELUP_STREAK"]
        if basicCoupons.contains(coupon.code) {
            // 对于周频率优惠券，需要检查本周是否已使用
            if coupon.usageFrequency == .weekly {
                let calendar = Calendar.current
                guard let currentWeekInterval = calendar.dateInterval(of: .weekOfYear, for: Date()) else {
                    return true
                }
                
                let usedThisWeek = user.couponUsageHistory.contains { record in
                    record.couponCode == coupon.code &&
                    currentWeekInterval.contains(record.usedDate)
                }
                
                return !usedThisWeek
            }
            return true
        }
        

        
        // 特殊优惠券解锁逻辑：需要满足特定条件才能解锁
        if coupon.code == "BIRTHDAY30" {
            // 生日月礼券需要完善个人信息后才能解锁
            return user.isMemberInfoComplete
        }
        
        if coupon.code == "MEMBER_INFO_COMPLETE" {
            // 会员信息完善礼券需要完善个人信息后才能解锁
            return user.isMemberInfoComplete
        }
        
        return false
    }
    
    func recordCouponUsage(_ coupon: Coupon) {
        guard var user = currentUser else { return }
        
        // 如果是现金券，使用专门的现金券使用方法
        if coupon.isCashVoucher {
            _ = useCashVoucher(couponCode: coupon.code)
            return
        }
        
        // 记录使用历史
        user.recordCouponUsage(coupon)
        
        // 标记用户拥有的礼券为已使用
        if let index = user.ownedCoupons.firstIndex(where: {
            $0.couponCode == coupon.code && !$0.isUsed
        }) {
            // 标记优惠券为已使用
            user.ownedCoupons[index].isUsed = true
        }
        
        currentUser = user
        saveUser(user)
    }
    
    // MARK: - Cash Voucher Quantity Management
    
    /// 获取现金券数量（基于配置）
    func getCashVoucherQuantity(for couponCode: String) -> Int {
        guard let user = currentUser else { return 0 }
        
        // 获取用户拥有的该类型现金券的未使用数量
        let ownedCount = user.ownedCoupons.filter { userCoupon in
            userCoupon.couponCode == couponCode &&
            !userCoupon.isUsed &&
            userCoupon.expiryDate > Date()
        }.count
        
        return ownedCount
    }
    
    /// 使用现金券（减少数量）
    func useCashVoucher(couponCode: String) -> Bool {
        guard var user = currentUser else { return false }
        
        // 查找第一张未使用的该类型现金券
        if let index = user.ownedCoupons.firstIndex(where: { userCoupon in
            userCoupon.couponCode == couponCode &&
            !userCoupon.isUsed &&
            userCoupon.expiryDate > Date()
        }) {
            // 标记为已使用
            user.ownedCoupons[index].isUsed = true
            
            // 记录使用历史
            let usageRecord = CouponUsageRecord(
                couponCode: couponCode,
                usedDate: Date()
            )
            user.couponUsageHistory.append(usageRecord)
            
            // 更新用户数据
            currentUser = user
            saveUser(user)
            
            return true
        }
        
        return false
    }
    

    
    func checkExpiringCoupons() {
        guard let user = currentUser else { return }
        
        let expiringCoupons = user.getExpiringCoupons(within: 3)
        
        // 这里可以触发通知或其他提醒机制
        if !expiringCoupons.isEmpty {
            // 检查即将过期的优惠券
            // 可以在这里添加推送通知逻辑
        }
    }
    
    // MARK: - 通知系统
    func showCouponUnlockNotification(couponTitle: String) {
        let message = currentLanguage == "zh" ? 
            "恭喜，您的\(couponTitle)礼券已经解锁，请及时使用。" :
            "Congratulations! Your \(couponTitle) coupon has been unlocked. Please use it in time."
        
        couponUnlockNotificationMessage = message
        showingCouponUnlockNotification = true
        
        // 3秒后自动隐藏通知
        DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
            self.showingCouponUnlockNotification = false
        }
    }
    
    // 为多个礼券显示解锁通知，每个礼券都需要用户点击OK确认
    private func showCouponUnlockNotifications(for couponCodes: [String]) {
        guard !couponCodes.isEmpty else { return }
        
        // 递归显示每个礼券的解锁通知
        showNextCouponUnlockAlert(couponCodes: couponCodes, index: 0)
    }
    
    @Published var pendingCouponAlerts: [String] = []
    @Published var currentAlertIndex: Int = 0
    
    private func showNextCouponUnlockAlert(couponCodes: [String], index: Int) {
        guard index < couponCodes.count else { return }
        
        let couponCode = couponCodes[index]
        if let coupon = availableCoupons.first(where: { $0.code == couponCode }) {
            let title = currentLanguage == "中文" ? coupon.title : coupon.englishTitle
            let message = currentLanguage == "中文" ? "\(title) 礼券已解锁！" : "\(title) coupon unlocked!"
            
            DispatchQueue.main.async {
                self.couponUnlockAlertMessage = message
                self.pendingCouponAlerts = Array(couponCodes.suffix(from: index + 1))
                self.currentAlertIndex = index
                self.showingCouponUnlockAlert = true
            }
        } else {
            // 如果找不到礼券，继续下一个
            showNextCouponUnlockAlert(couponCodes: couponCodes, index: index + 1)
        }
    }
    
    func handleCouponUnlockAlertDismiss() {
        showingCouponUnlockAlert = false
        
        // 显示下一个礼券解锁提示
        if !pendingCouponAlerts.isEmpty {
            let nextCouponCode = pendingCouponAlerts.removeFirst()
            showNextCouponUnlockAlert(couponCodes: [nextCouponCode] + pendingCouponAlerts, index: 0)
        }
    }
    
    func activateMemberInfoCompletionCoupon() {
        guard let user = currentUser, user.isMemberInfoComplete else { return }
        
        var unlockedCoupons: [String] = []
        
        // 检查是否已经拥有会员信息完善礼券
        let hasMemberInfoCoupon = user.ownedCoupons.contains { userCoupon in
            userCoupon.couponCode == "MEMBER_INFO_COMPLETE"
        }
        
        // 如果还没有，则发放会员信息完善礼券
        if !hasMemberInfoCoupon {
            grantCouponToUserSilently(couponCode: "MEMBER_INFO_COMPLETE", relativeDuration: .days(30))
            unlockedCoupons.append("MEMBER_INFO_COMPLETE")
        }
        
        // 检查是否已经拥有生日月礼券
        let hasBirthdayCoupon = user.ownedCoupons.contains { userCoupon in
            userCoupon.couponCode == "BIRTHDAY30"
        }
        
        // 如果还没有，则发放生日月礼券
        if !hasBirthdayCoupon {
            grantCouponToUserSilently(couponCode: "BIRTHDAY30", relativeDuration: .years(50))
            unlockedCoupons.append("BIRTHDAY30")
        }
        
        // 为每个解锁的礼券显示提示
        showCouponUnlockNotifications(for: unlockedCoupons)
    }
    
    // 为新注册的Level 1会员分配初始优惠券
    private func grantInitialCouponsForNewUser() {
        guard let user = currentUser, user.membershipLevel == .lv1 else { return }
        
        // 为Level 1会员分配初始优惠券：新会员礼券，周末特惠，Highball，Free Coffee，Mystery Gift
        // 这些初始礼券静默发放，不显示解锁提示
        let initialCoupons = ["NEWMEMBER5", "WEEKEND50", "HIGHBALL", "CALFCOFFEE", "MYSTERYGIFT"]
        
        for couponCode in initialCoupons {
            grantCouponToUserSilently(couponCode: couponCode, relativeDuration: .days(30))
        }
    }
    
    // MARK: - Cash Voucher Purchase Processing
    private func processCashVoucherPurchase(paymentMethod: PaymentMethod) {
        guard var user = currentUser else { return }
        
        // 使用参数化配置生成现金券，根据配置的数量生成对应张数
        var totalVouchersAdded = 0
        
        for (index, couponCode) in AppConfig.CashVoucherPackage.voucherCodes.enumerated() {
            let quantity = AppConfig.CashVoucherPackage.voucherQuantities[index]
            
            // 为每种现金券生成指定数量的优惠券
            for _ in 0..<quantity {
                let userCoupon = UserCoupon(
                    couponCode: couponCode,
                    grantedDate: Date(),
                    relativeDuration: .years(AppConfig.CashVoucherPackage.voucherValidityYears)
                )
                
                // 添加到用户的优惠券列表
                user.ownedCoupons.append(userCoupon)
                totalVouchersAdded += 1
            }
        }
        
        // 更新当前用户对象
        currentUser = user
        saveUser(user)
        
        // 显示购买成功提示
        DispatchQueue.main.async {
            let message = self.currentLanguage == "zh" ? 
                "现金券购买成功！\(totalVouchersAdded)张现金券已加入您的优惠券列表中。" : 
                "Cash vouchers purchased successfully! \(totalVouchersAdded) cash vouchers have been added to your coupon list."
            self.couponUnlockAlertMessage = message
            self.showingCouponUnlockAlert = true
        }
    }
    
    // MARK: - Invite System
    
    // 验证邀请码并返回推荐人ID
    // 注意：现在只验证动态4位数字邀请码
    func validateInviteCode(_ inviteCode: String?) -> String? {
        guard let code = inviteCode, !code.isEmpty else { return nil }
        
        // 验证是否为4位数字格式
        guard code.count == 4, code.allSatisfy({ $0.isNumber }) else { return nil }
        
        // 查找所有用户，验证动态邀请码
        let allPhones = getAllRegisteredPhones()
        for phone in allPhones {
            if let user = loadUser(phoneNumber: phone) {
                let userDynamicCode = generateDynamicInviteCode(for: user)
                if userDynamicCode == code {
                    return user.memberID
                }
            }
        }
        return nil
    }
    
    // 生成用户的动态邀请码
    private func generateDynamicInviteCode(for user: User) -> String {
        let currentTime = Date().timeIntervalSince1970
        let timeSlot = Int(currentTime / (72 * 3600)) // 72小时时间槽
        
        let userIdHash = user.id.hashValue
        let combinedHash = abs(userIdHash ^ timeSlot)
        let fourDigitCode = String(format: "%04d", combinedHash % 10000)
        return fourDigitCode
    }
    
    // 处理邀请奖励
    func processInviteReward(referrerID: String, newUserID: String) {
        // 查找推荐人
        guard let referrer = findUserByMemberID(referrerID) else { return }
        
        // 给推荐人发放3元现金礼券
        grantCashVoucher(to: referrer, amount: "3")
        
        // 给新用户发放3元现金礼券
        if let newUser = findUserByMemberID(newUserID) {
            grantCashVoucher(to: newUser, amount: "3")
        }
        
        // 更新推荐人的邀请记录
        updateInviteRecord(referrerID: referrerID, newUserID: newUserID)
    }
    
    // 发放现金礼券
    private func grantCashVoucher(to user: User, amount: String) {
        var updatedUser = user
        let voucher = UserCoupon(
            couponCode: "INVITE_REWARD_\(amount)",
            grantedDate: Date(),
            relativeDuration: .days(30)
        )
        updatedUser.ownedCoupons.append(voucher)
        saveUser(updatedUser)
        
        // 如果是当前用户，更新当前用户状态
        if currentUser?.memberID == user.memberID {
            currentUser = updatedUser
        }
    }
    
    // 更新邀请记录
    private func updateInviteRecord(referrerID: String, newUserID: String) {
        guard var referrer = findUserByMemberID(referrerID),
              let newUser = findUserByMemberID(newUserID) else { return }
        
        let inviteRecord = InviteRecord(
            invitedMemberID: newUserID,
            invitedPhone: newUser.phoneNumber,
            isSuccessful: true
        )
        
        referrer.inviteHistory.append(inviteRecord)
        saveUser(referrer)
        
        // 如果是当前用户，更新当前用户状态
        if currentUser?.memberID == referrer.memberID {
            currentUser = referrer
        }
    }
    
    // 根据会员ID查找用户
    private func findUserByMemberID(_ memberID: String) -> User? {
        let allPhones = getAllRegisteredPhones()
        for phone in allPhones {
            if let user = loadUser(phoneNumber: phone), user.memberID == memberID {
                return user
            }
        }
        return nil
    }
    
    // 获取所有注册用户的手机号
    private func getAllRegisteredPhones() -> [String] {
        let defaults = UserDefaults.standard
        let allKeys = defaults.dictionaryRepresentation().keys
        return allKeys.compactMap { key in
            if key.hasPrefix(AppConfig.StorageKeys.userPrefix) {
                return String(key.dropFirst(AppConfig.StorageKeys.userPrefix.count)) // 移除userPrefix前缀
            }
            return nil
        }
    }
    
    // 获取用户的邀请码
    func getUserInviteCode() -> String? {
        guard let user = currentUser else { return nil }
        return generateDynamicInviteCode(for: user)
    }
    
    // 获取邀请统计信息
    func getInviteStats() -> (totalInvites: Int, successfulInvites: Int) {
        guard let user = currentUser else { return (0, 0) }
        let total = user.inviteHistory.count
        let successful = user.inviteHistory.filter { $0.isSuccessful }.count
        return (total, successful)
    }
    
    // MARK: - Sample Data
    private func loadSampleData() {
        // 恢复登录界面显示
        currentUser = nil
        isGuestMode = false
        
        // 清空用户优惠券
        ownedCoupons = []
        
        // 注意：菜单和优惠券数据现在在init中异步加载
        // 这个方法保留用于其他需要同步重置数据的场景
    }
    
    // MARK: - 订单历史持久化
    private func loadUserOrders() {
        if let currentUser = currentUser {
            loadOrdersForUser(userId: currentUser.id)
        }
    }
    
    private func loadOrdersForUser(userId: UUID) {
        let key = AppConfig.StorageKeys.ordersPrefix + userId.uuidString
        if let ordersData = UserDefaults.standard.data(forKey: key) {
            do {
                let userOrders = try JSONDecoder().decode([Order].self, from: ordersData)
                self.orders = userOrders
            } catch {
                self.orders = []
            }
        }
    }
    
    private func saveOrdersForCurrentUser() {
        guard let currentUser = currentUser else { return }
        let key = AppConfig.StorageKeys.ordersPrefix + currentUser.id.uuidString
        do {
            let ordersData = try JSONEncoder().encode(orders)
            UserDefaults.standard.set(ordersData, forKey: key)
        } catch {
            // 保存失败，静默处理
        }
    }
    
    // 重写createOrder方法以包含持久化
    func createOrderWithPersistence(paymentMethod: PaymentMethod, specialInstructions: String? = nil, appliedCoupon: Coupon? = nil, pointsUsed: Int = 0, reservationTime: Date? = nil, reservationInfo: ReservationConfig.ReservationInfo? = nil) -> Order {
        let order = createOrder(
            paymentMethod: paymentMethod,
            specialInstructions: specialInstructions,
            appliedCoupon: appliedCoupon,
            pointsUsed: pointsUsed,
            reservationTime: reservationTime,
            reservationInfo: reservationInfo
        )
        saveOrdersForCurrentUser()
        return order
    }
    
    // 重写updateOrderStatus方法以包含持久化
    func updateOrderStatusWithPersistence(_ orderId: UUID, status: OrderStatus) {
        updateOrderStatus(orderId, status: status)
        saveOrdersForCurrentUser()
        // 如果用户数据有变化（如积分增加），也保存用户数据
        if let user = currentUser {
            saveUser(user)
        }
    }
    
    // MARK: - 测试数据管理
    func clearAllTestData() {
        if AppConfig.enableDebugLogging {
            print("[DEBUG] 开始清除所有测试数据")
        }
        
        // 清除所有测试用户数据
        let testPhoneNumbers = ["88888888", "66666666", "99999999", "77777777"]
        for phoneNumber in testPhoneNumbers {
            let userKey = AppConfig.StorageKeys.userPrefix + phoneNumber
            let hadUserData = UserDefaults.standard.object(forKey: userKey) != nil
            UserDefaults.standard.removeObject(forKey: userKey)
            
            if AppConfig.enableDebugLogging && hadUserData {
                print("[DEBUG] 已清除测试用户数据: \(phoneNumber)")
            }
            
            // 如果有对应的用户ID，也清除订单数据
            if let testUser = loadTestUser(phoneNumber: phoneNumber) {
                let orderKey = AppConfig.StorageKeys.ordersPrefix + testUser.id.uuidString
                let hadOrderData = UserDefaults.standard.object(forKey: orderKey) != nil
                UserDefaults.standard.removeObject(forKey: orderKey)
                
                if AppConfig.enableDebugLogging && hadOrderData {
                    print("[DEBUG] 已清除测试用户订单数据: \(phoneNumber) (ID: \(testUser.id.uuidString))")
                }
            }
        }
        
        // 清除当前会话数据
        let hadCurrentUser = currentUser != nil
        currentUser = nil
        orders.removeAll()
        cartItems.removeAll()
        isGuestMode = false
        
        if AppConfig.enableDebugLogging {
            print("[DEBUG] 已清除当前会话数据，之前有用户登录: \(hadCurrentUser)")
            print("[DEBUG] 所有测试数据清除完成")
        }
    }
    
    // MARK: - 用户积分管理
    func clearUserInteractionPoints(phoneNumber: String) {
        // 清除指定用户的积分记录
        if currentUser?.phoneNumber == phoneNumber {
            // 积分记录已清除
        }
    }
    
    func setUserPoints(phoneNumber: String, points: Int) {
        // 如果是当前用户，直接设置积分
        if var user = currentUser, user.phoneNumber == phoneNumber {
            user.points = points
            currentUser = user
            saveUser(user)
            return
        }
        
        // 如果不是当前用户，加载用户数据并设置积分
        if var user = loadUser(phoneNumber: phoneNumber) {
            user.points = points
            saveUser(user)
        }
    }
    
    // 测试代码已移除
}